﻿using System;
using System.Activities.Validation;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using IFRS.DataAccess.DAL;
using IFRS_Global;
using IFRS.Model;
using IFRS.Web;

/// <summary>
/// Summary description for Extension
/// </summary>
/// 

    public static class Extension
    {
        public static RequiredFieldValidator SetRequiredField(this RequiredFieldValidator requiredFieldValidator, Label label, System.Web.UI.Control controlToValidate, Button button, string message = "", ValidatorDisplay display = ValidatorDisplay.Dynamic)
        {
            if (message == string.Empty)
            {
                message = Resources.ifrsField.PLEASE_IDENTIFIEND;
                requiredFieldValidator.ErrorMessage = string.Format("{0}{1}", message, label.Text);
            }
            else
            {
                requiredFieldValidator.ErrorMessage = message;
            }

            requiredFieldValidator.ControlToValidate = controlToValidate.ID;
            requiredFieldValidator.Display = display;
            // requiredFieldValidator.ErrorMessage = string.Format("{0}{1}", message, label.Text);
            requiredFieldValidator.ForeColor = Color.Red;
            requiredFieldValidator.ValidationGroup = button.ValidationGroup;
            requiredFieldValidator.CssClass = "required";
            return requiredFieldValidator;
        }

        #region
        public static void SetStandardField(this IStandardField row)
        {
            row.CreatedDate = DateTime.Now;
            row.CreatedBy = SessionManager.IFRS_EMPLOYEE_ID;
            row.CreatedCostCenter = SessionManager.IFRS_COST_CENTER;
            row.CreatedBranch = SessionManager.IFRS_BRANCH;
            row.UpdatedDate = DateTime.Now;
            row.UpdatedBy = SessionManager.IFRS_EMPLOYEE_ID;
            row.UpdatedCostCenter = SessionManager.IFRS_COST_CENTER;
            row.UpdatedBranch = SessionManager.IFRS_BRANCH;
        }
        public static DropDownList SetData(this DropDownList dropDownList, string ddlType)
        {
            dropDownList.SetData(ddlType, "", false, false);
            return dropDownList;
        }
        public static DropDownList SetData(this DropDownList dropDownList, string ddlType, string firstText)
        {
            dropDownList.SetData(ddlType, firstText, false, false);
            return dropDownList;
        }
        public static DropDownList SetData(this DropDownList dropDownList, string ddlType, string firstText, bool IsSearch)
        {
            dropDownList.SetData(ddlType, "", IsSearch, false);
            return dropDownList;
        }
        public static DropDownList SetData(this DropDownList dropDownList, string ddlType, string firstText, bool IsSearch, bool IsRequire)
        {
            if (ddlType == DDL_TYPE.StatusConfirmed.ToString())
            {
                dropDownList.Items.Add(new ListItem("สร้างรายการ", "0"));
                dropDownList.Items.Add(new ListItem("ยืนยัน", "1"));
            }
            else
            {
                DataTable dt = new DataTable();
                dt = new DDL_CENTER().GET_DDL(ddlType);
                dropDownList.DataSource = dt;
                dropDownList.DataTextField = "TXT_DLL";
                dropDownList.DataValueField = "VALUE_DLL";
                dropDownList.DataBind();
            }
            if (!string.IsNullOrEmpty(firstText))
                dropDownList.Items.Insert(0, new ListItem { Text = "ทั้งหมด", Value = "" });

            if (IsRequire)
                dropDownList.Items.Insert(0, new ListItem { Text = "กรุณาเลือก", Value = "" });

            if (IsSearch)
                dropDownList.Items.Insert(0, new ListItem { Text = "ทั้งหมด", Value = "" });


            if (!IsRequire && !IsSearch)
                dropDownList.Items.Insert(0, new ListItem { Text = "", Value = "" });

            return dropDownList;
        }
        #endregion

        #region "Conversion Helper"

        
        
        #endregion
    }
    public static class ValueTypeExt
    {
        public static string NoEmpty(this string s)
        {
            return String.IsNullOrWhiteSpace(s) ? null : s.Trim();
        }

        public static object AsDBValue(this string s)
        {
            return String.IsNullOrWhiteSpace(s) ? DBNull.Value : (object)s.Trim();
        }

        public static object AsDBValue<T>(this T value)
        {
            return value == null ? DBNull.Value : (object)value;
        }

        public static string AsString(this SqlParameter param)
        {
            return param.Value == DBNull.Value ? null : (string)param.Value;
        }

        public static string AsStringNull(this SqlParameter param)
        {
            return param.Value == DBNull.Value ? "" : (string)param.Value;
        }
        public static decimal? AsDecimal(this SqlParameter param)
        {
            return param.Value == DBNull.Value ? (decimal?)null : (decimal)param.Value;
        }
        public static int AsInt32(this string s)
        {
            return s == "" ? 0 : Convert.ToInt32(s);
        }
        public static int? AsIntIsnull(this string s)
        {
            return s == "" ? (int?)null : Convert.ToInt32(s);
        }
        public static decimal? AsDecimal(this string value)
        {
            decimal d;
            return String.IsNullOrWhiteSpace(value) ? (decimal?)null : Decimal.TryParse(value, out d) ? d : (decimal?)null;
        }   
        public static decimal ParseDecimal(this string value)
        {
            return Convert.ToDecimal(value);
        }

        public static string DateToString(this DateTime value)
        {
            //return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToDateTime(value).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) : string.Empty;

            if (string.IsNullOrEmpty(Convert.ToString(value))) return string.Empty;

            var date = Convert.ToDateTime(value).ToString("dd/MM/yyyy");
            var dateArr = date.Split('/');
            if (dateArr.Length <= 0) return string.Empty;

            var day = Convert.ToString(dateArr[0]);
            var month = Convert.ToString(dateArr[1]);
            var year = Convert.ToString(Convert.ToInt32(dateArr[2]) + 543);
            return string.Format("{0}/{1}/{2}",day,month,year);
        }

        public static string DateToString(this DateTime? value)
        {
            //return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToDateTime(value).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) : string.Empty;

            if (string.IsNullOrEmpty(Convert.ToString(value))) return string.Empty;

            var date = Convert.ToDateTime(value).ToString("dd/MM/yyyy");
            var dateArr = date.Split('/');
            if (dateArr.Length <= 0) return string.Empty;

            var day = Convert.ToString(dateArr[0]);
            var month = Convert.ToString(dateArr[1]);
            var year = Convert.ToString(Convert.ToInt32(dateArr[2]) + 543);
            return string.Format("{0}/{1}/{2}", day, month, year);
        }

        public static string DecimalToString(this decimal value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }

        public static string DecimalToString(this decimal? value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }

        public static string IntToString(this int value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }

        public static string IntToString(this int? value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }
        public static bool? AsConfirmed(this string value)
        {
            if (!string.IsNullOrEmpty(value)) { return value == "1" ? true : false; }
            else return null;           
        }
        public static bool? AsConfirmedIsnull(this string value)
        {
            return string.IsNullOrEmpty(value) ? (bool?)null : ( value == "1" ? true : false );            
        }

        public static DateTime? StringToDateAllowNull(this string value)
        {
            if (string.IsNullOrEmpty(value)) return null;

            var dateArr = value.Split('/');
            if (dateArr.Length <= 0) return null;

            var day = Convert.ToString(dateArr[0]);
            var month = Convert.ToString(dateArr[1]);
            var year = Convert.ToString(Convert.ToInt32(dateArr[2]) - 543);

            var date = string.Format("{0}/{1}/{2}", day, month, year);

            return DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        }

        public static DateTime StringToDate(this string value)
        {
            var dateArr = value.Split('/');

            var day = Convert.ToString(dateArr[0]);
            var month = Convert.ToString(dateArr[1]);
            var year = Convert.ToString(Convert.ToInt32(dateArr[2]) - 543);

            var date = string.Format("{0}/{1}/{2}", day, month, year);

            return DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        }

        public static string AsString(this int value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }
        public static string AsString(this int? value)
        {
            return !string.IsNullOrEmpty(Convert.ToString(value)) ? Convert.ToString(value) : string.Empty;
        }
    }

    public static class GridViewHelper
    {
        public static string LastSortField = "LastSortField";
        public static string Descending = "Descending";
        public static string DESC = " DESC";
        public static string ASC = " ASC";
        public static string KeyValue = "KeyValue";

        public static T GetRow<T>(this GridViewRow row) where T : DataRow
        {
            DataRowView drv = (row.DataItem as DataRowView);
            return drv == null ? null : (T)drv.Row;
        }

        public static void SetLinkAttribute(this GridViewRow row, string ID, string fieldName, Action<LinkButton> actionEach = null)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                LinkButton control = (LinkButton)row.FindControl(ID);
                if (control != null)
                {
                    control.Attributes[fieldName] = DataBinder.Eval(row.DataItem, fieldName, "{0}");
                    control.Attributes.Add("_SEQ_NUMBER", (row.DataItemIndex + 1).ToString());
                    if (ID == "lnkDelete")
                        control.Attributes.Add("OnClick", "if(!confirm(\"" + Resources.ifrsResource.ConfirmDelete + "\")) return false;");
                    if (actionEach != null)
                    {
                        actionEach(control);
                    }
                }
            }
        }
        public static void SetLinkInVisibleOnEdit(this GridView gridView, string linkName, string attributeName, HiddenField compareWithID, Action<LinkButton> actionEach = null)
        {
            gridView.RowCreated += (sender, e) => e.Row.PreRender += (s, a) =>
            {
                LinkButton control = (LinkButton)e.Row.FindControl(linkName);
                if (control != null)
                {
                    decimal? id = compareWithID.Value.AsDecimal();
                    if (e.Row.Attributes["deleted"] != "deleted")
                        control.Visible = id == null || id != control.Attributes[attributeName].AsDecimal();
                    if (actionEach != null)
                        actionEach(control);
                }
            };
        }
        public static void SetRadioAttribute(this GridViewRow row, string ID, string fieldName, Action<RadioButton> actionEach = null)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                RadioButton control = (RadioButton)row.FindControl(ID);
                if (control != null)
                {
                    control.Attributes[fieldName] = DataBinder.Eval(row.DataItem, fieldName, "{0}");
                    if (actionEach != null)
                    {
                        actionEach(control);
                    }
                }
            }
        }
        public static void SetButtonAttribute(this GridViewRow row, string ID, string fieldName, Action<Button> actionEach = null)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                Button control = (Button)row.FindControl(ID);
                if (control != null)
                {
                    control.Attributes[fieldName] = DataBinder.Eval(row.DataItem, fieldName, "{0}");
                    if (actionEach != null)
                    {
                        actionEach(control);
                    }
                }
            }
        }

        public static void SetRowAttribute(this GridViewRow row, string fieldName)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                row.Attributes[fieldName] = DataBinder.Eval(row.DataItem, fieldName, "{0}");
            }
        }

        public static void SetStyleForAdded(this GridViewRow row, bool condition)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                if (condition)
                {
                    row.ForeColor = System.Drawing.Color.Blue;
                }
            }
        }

        public static void SetStyleForEdited(this GridViewRow row, bool condition)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                if (condition)
                {
                    row.ForeColor = System.Drawing.Color.Blue;
                }
            }
        }

      
        public static void SetCheckBox(this GridViewRow row, string checkBoxName, bool withValue, Action<CheckBox> moreAction = null)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                var chkbox = row.FindControl(checkBoxName) as CheckBox;
                if (withValue)
                {
                    if (chkbox != null)
                    {
                        chkbox.Checked = withValue;
                        if (moreAction != null) moreAction(chkbox);
                    }
                }
            }
        }

      
        public static void SetLabel(this GridViewRow row, string ID, string text)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                var label = row.FindControl(ID) as Label;
                if (label != null)
                {
                    label.Text = text;
                }
            }
        }

        public static string GetRowSeq(this object sender)
        {
            return ((LinkButton)sender).Attributes["_SEQ_NUMBER"];
        }

        public static string Data = "Data";

        public static void BindDataAndSaveToViewState(this GridView gridView, DataTable dt, StateBag viewState, string withDefaultSortExpr = null)
        {
            string sortExpr = gridView.GetCurrentSortParam() ?? withDefaultSortExpr;
            if (string.IsNullOrEmpty(sortExpr))
            {
                gridView.DataSource = dt;
            }
            else
            {
                var dv = dt.DefaultView;
                dv.Sort = sortExpr;
                gridView.DataSource = dv;
            }
            gridView.DataBind();
            viewState[gridView.ID + Data] = dt;
        }

        public static T GetDataInViewState<T>(this GridView gridView, StateBag viewState) where T : DataTable, new()
        {
            return (viewState[gridView.ID + Data] as T) ?? new T();
        }

        public static string GetCurrentSortParam(this GridView gridView)
        {
            string lastSortField = gridView.Attributes[gridView.ID + LastSortField];
            bool descending = Convert.ToBoolean(gridView.Attributes[gridView.ID + Descending]);
            return String.IsNullOrEmpty(lastSortField) ? null : lastSortField + (descending ? DESC : ASC);
        }

        public static string GetToggleSortParam(this GridView gridView, string sortExpression)
        {
            string lastSortField = gridView.Attributes[gridView.ID + LastSortField];
            bool descending = Convert.ToBoolean(gridView.Attributes[gridView.ID + Descending]);

            string result = null;
            if (lastSortField == null || (lastSortField.Equals(sortExpression) && !descending))
            {
                descending = true;
                result = sortExpression + DESC;
            }
            else
            {
                descending = false;
                result = sortExpression + ASC;
            }
            gridView.Attributes[gridView.ID + LastSortField] = sortExpression;
            gridView.Attributes[gridView.ID + Descending] = descending.ToString();
            return result;
        }

      
      
      

        public static void InitCheckedValues(this GridView gridView, List<string> values, StateBag viewState)
        {
            viewState[gridView.ID + "__checked_values"] = values.ToArray();
        }

        public static void ClearCheckedValues(this GridView gridView, StateBag viewState)
        {
            viewState[gridView.ID + "__checked_values"] = null;
        }

     
    

        public static void SetCheckBox(this GridViewRow row, string checkBoxName, string withRememberFieldName, List<string> CheckedValues, Action<CheckBox> moreAction = null)
        {
            if (row.RowIndex > -1 && row.RowType == DataControlRowType.DataRow)
            {
                var chkbox = row.FindControl(checkBoxName) as CheckBox;
                if (chkbox != null)
                {
                    string value = DataBinder.Eval(row.DataItem, withRememberFieldName, "{0}");
                    chkbox.Checked = CheckedValues != null ? CheckedValues.Contains(value) : false;
                    if (moreAction != null) moreAction(chkbox);

                    GridView gridView = row.NamingContainer as GridView;
                    if (gridView != null)
                    {
                        gridView.Attributes["__check_box_name"] = checkBoxName;
                        row.Attributes["__val"] = value;
                    }
                }
            }
        }

    }

    public static class ConvertHelper
    {
        public static List<T> ConvertDataTableToObject<T>(DataTable dt, List<T> objList)
        {
            Type type = typeof(T);
            T obj;
            obj = (T)Activator.CreateInstance(type);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string ColumnName = dt.Columns[j].ColumnName;
                    PropertyInfo info = type.GetProperty(ColumnName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                    if (info != null)
                    {
                        object val = dt.Rows[i][j];
                        if (val != DBNull.Value)
                        {
                            info.SetValue(obj, val, null);
                        }
                    }
                }
                objList.Add(obj);
            }
            return objList;
        }
    }
